#include "connectionthread.h"
#include <QDebug>
#include <QAbstractSocket>

ConnectionThread::ConnectionThread(int sockDescriptor, QObject *parent):
        QThread(parent)
{
    ConnectionThread::sockDescriptor = sockDescriptor;
}

ConnectionThread::~ConnectionThread(void)
{
}

void ConnectionThread::newConnection(Connection *pConnection)
{
    connect(pConnection, SIGNAL(error(Connection*)),this,SLOT(errorConnection(Connection*)));
    connect(pConnection, SIGNAL(disconnected()), this, SLOT(disconnected()));
    connect(pConnection, SIGNAL(destroyed()), this, SLOT(destroyed()));
    connect(pConnection, SIGNAL(readyForUse(Connection *)), this, SLOT(connectionReady(Connection *)));
}

void ConnectionThread::disconnected()
{
    if(Connection *pConnection = qobject_cast<Connection *>(sender()))
    {
        removeConnection(pConnection);
        globManager.removeConnection(pConnection);
    }
}

void ConnectionThread::removeConnection(Connection *pConnection)
{
    pConnection->deleteLater();
}

void ConnectionThread::destroyed(QObject *pObj)
{
    this->exit();
}

void ConnectionThread::run()
{
    try
    {
        Connection *pConnection = new Connection();
        pConnection->setSocketDescriptor(sockDescriptor);
        emit newConnection(pConnection);
        pConnection->initConnection();
    }
    catch(...)
    {
        qCritical("Error in file: %s, line: %d", __FILE__, __LINE__);
    }
    exec();
}

void ConnectionThread::errorConnection(Connection *pConnection)
{
    removeConnection(pConnection);
    globManager.removeConnection(pConnection);
}

void ConnectionThread::connectionReady(Connection *pConnection)
{
    globManager.newConnection(pConnection);
    connect(pConnection, SIGNAL(readData(sockTypes,QByteArray)),&globManager,SLOT(readData(sockTypes,QByteArray)));
}
